package org.unisinos.gc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;

import org.unisinos.gc.vo.Area;

public abstract class AreaDAO {

	public static Collection<Area> getAreaList() throws SQLException {
		Collection<Area> areaList = null;
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			con = ConnectionManager.getConnection();
			stmt = con.createStatement();
			rs = stmt.executeQuery("select * from area");
			areaList = new ArrayList<Area>();
			while(rs.next()) {
				areaList.add(new Area(rs.getInt("codigo"), rs.getString("nome")));
			}
			
		}finally {
			try {
				if (con!=null)con.close();
				if (stmt!=null)stmt.close();
				if (rs!=null)rs.close();
			}catch (Exception e) {}
		}
		return areaList;
	}
	
	public static Area getArea(int codigo) throws SQLException {
		Area area = null;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con = ConnectionManager.getConnection();
			ps = con.prepareStatement("select * from area where codigo = ?");
			ps.setInt(1, codigo);
			rs = ps.executeQuery();
			while(rs.next()) {
				area = new Area(rs.getInt("codigo"), rs.getString("nome"));
				break;
			}
			
		} finally {
			try {
				if (con!=null)con.close();
				if (ps!=null)ps.close();
				if (rs!=null)rs.close();
			}catch (Exception e) {}
		}
		return area;
	}
	
	public static void addArea(Area area) throws SQLException {
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = ConnectionManager.getConnection();
			ps = con.prepareStatement("INSERT INTO area(codigo, nome) VALUES (?, ?)");
			ps.setInt(1, area.getCodigo());
			ps.setString(2, area.getNome());
			ps.execute();
		} finally {
			try {
				if (con!=null)con.close();
				if (ps!=null)ps.close();
			}catch (Exception e) {}
		}
	}
	
	public static void deleteArea(int codigo) throws SQLException {
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = ConnectionManager.getConnection();
			ps = con.prepareStatement("delete from area where codigo = ?");
			ps.setInt(1, codigo);
			ps.execute();
		} finally {
			try {
				if (con!=null)con.close();
				if (ps!=null)ps.close();
			}catch (Exception e) {}
		}
	}
	
	public static void updateArea(Area area) throws SQLException {
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = ConnectionManager.getConnection();
			ps = con.prepareStatement("UPDATE area SET nome=? WHERE codigo=?");
			ps.setString(1, area.getNome());
			ps.setInt(2, area.getCodigo());
			ps.execute();
		} finally {
			try {
				if (con!=null)con.close();
				if (ps!=null)ps.close();
			}catch (Exception e) {}
		}
	}
}
